<template>
  <div class="page-content parking-edit">
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">{{ isEdit ? '编辑停车场' : '添加停车场' }}</h1>
        <p class="text-gray-500 mt-2">{{
          isEdit ? '修改停车场信息和配置' : '创建新的停车场记录'
        }}</p>
      </div>
      <el-button @click="goBack">
        <el-icon><Back /></el-icon>返回
      </el-button>
    </div>

    <el-card shadow="hover">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        status-icon
        require-asterisk-position="right"
        scroll-to-error
      >
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">基本信息</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="停车场名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入停车场名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入停车场位置" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="8" :sm="24">
            <el-form-item label="总车位数" prop="totalSpaces">
              <el-input-number
                v-model="form.totalSpaces"
                :min="1"
                :precision="0"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="8" :sm="24">
            <el-form-item label="可用车位数" prop="availableSpaces">
              <el-input-number
                v-model="form.availableSpaces"
                :min="0"
                :max="form.totalSpaces"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="8" :sm="24">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择停车场状态" style="width: 100%">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 收费信息 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">收费标准</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="小时收费(元)" prop="fee.hourly">
              <el-input-number
                v-model="form.fee.hourly"
                :min="0"
                :precision="1"
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="日封顶收费(元)" prop="fee.daily">
              <el-input-number
                v-model="form.fee.daily"
                :min="0"
                :precision="1"
                :step="5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 详情信息 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">详细信息</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="营业时间" prop="openingHours">
              <el-input v-model="form.openingHours" placeholder="请输入营业时间,例如: 24小时开放" />
            </el-form-item>
          </el-col>

          <el-col :lg="12" :md="12" :sm="24">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="停车场介绍" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="4"
                placeholder="请输入停车场详细介绍"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="停车场主图">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleImageChange"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <div v-else class="avatar-uploader-wrapper">
                  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  <div class="mt-2 text-sm text-gray-500">点击上传主图</div>
                </div>
              </el-upload>
              <div class="mt-2 text-sm text-gray-500">推荐尺寸: 800x400px, 格式: JPG/PNG</div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="设施情况">
              <el-select
                v-model="form.features"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入设施情况"
                style="width: 100%"
              >
                <el-option
                  v-for="item in facilityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 表单操作 -->
          <el-col :span="24" class="mt-4">
            <el-form-item>
              <div class="flex justify-center gap-4">
                <el-button @click="goBack">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
                <el-button v-if="isEdit" type="danger" @click="confirmDelete">删除</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Back, Plus } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  import type { ParkingLotType } from '@/types/parking'
  import { ParkingLotStatus } from '@/types/parking'

  const route = useRoute()
  const router = useRouter()
  const formRef = ref<FormInstance>()
  const parkingLotId = ref(route.query.id ? Number(route.query.id) : 0)
  const isEdit = computed(() => !!parkingLotId.value)
  const imageUrl = ref('')
  const isLoading = ref(false)

  // 停车场状态选项
  const statusOptions = [
    { label: '营业中', value: ParkingLotStatus.OPEN },
    { label: '已满', value: ParkingLotStatus.FULL },
    { label: '维护中', value: ParkingLotStatus.MAINTENANCE },
    { label: '已关闭', value: ParkingLotStatus.CLOSED }
  ]

  // 设施选项
  const facilityOptions = [
    { label: '视频监控', value: '视频监控' },
    { label: '24小时值守', value: '24小时值守' },
    { label: '自动计费', value: '自动计费' },
    { label: '充电桩', value: '充电桩' },
    { label: '无障碍设施', value: '无障碍设施' },
    { label: '消防设备', value: '消防设备' },
    { label: '照明系统', value: '照明系统' },
    { label: 'WiFi覆盖', value: 'WiFi覆盖' },
    { label: '停车引导系统', value: '停车引导系统' }
  ]

  // 表单数据
  const form = reactive<ParkingLotType>({
    id: 0,
    name: '',
    location: '',
    totalSpaces: 100,
    availableSpaces: 100,
    status: ParkingLotStatus.OPEN,
    fee: {
      hourly: 10,
      daily: 50
    },
    openingHours: '24小时开放',
    imageUrl: '',
    description: '',
    features: [],
    contactPhone: '',
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString()
  })

  // 表单验证规则
  const rules = {
    name: [
      { required: true, message: '请输入停车场名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    location: [{ required: true, message: '请输入停车场位置', trigger: 'blur' }],
    status: [{ required: true, message: '请选择停车场状态', trigger: 'change' }],
    openingHours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }],
    description: [
      { required: true, message: '请输入停车场介绍', trigger: 'blur' },
      { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
    ],
    'fee.hourly': [{ required: true, message: '请输入小时收费', trigger: 'blur' }],
    'fee.daily': [{ required: true, message: '请输入日封顶收费', trigger: 'blur' }]
  }

  // 获取停车场详情
  const fetchParkingLotDetail = async () => {
    if (!isEdit.value) return

    isLoading.value = true

    try {
      // 模拟API请求
      setTimeout(() => {
        // 这里应该是从API获取数据，这里使用模拟数据
        const data = {
          id: parkingLotId.value,
          name: '东门停车场',
          location: '景区东门入口处',
          totalSpaces: 200,
          availableSpaces: 45,
          status: ParkingLotStatus.OPEN,
          fee: {
            hourly: 10,
            daily: 50
          },
          openingHours: '24小时开放',
          imageUrl: `https://picsum.photos/800/400?random=${parkingLotId.value}`,
          description:
            '东门停车场位于景区东门入口处，交通便利，设施完善。停车场共有200个车位，包括普通车位、残疾人专用车位和新能源车专用充电车位。停车场采用自动化管理系统，配备高清监控和照明设施，确保车辆安全。',
          features: [
            '视频监控',
            '24小时值守',
            '自动计费',
            '充电桩',
            '无障碍设施',
            '消防设备',
            '照明系统'
          ],
          contactPhone: '0755-12345678',
          createTime: '2023-01-01 00:00:00',
          updateTime: new Date().toISOString()
        }

        // 更新表单数据
        Object.assign(form, data)
        imageUrl.value = data.imageUrl

        isLoading.value = false
      }, 1000)

      // 实际API调用示例:
      // const res = await parkingService.getParkingLotDetail(parkingLotId.value)
      // if (res.code === 200) {
      //   Object.assign(form, res.data)
      //   imageUrl.value = res.data.imageUrl
      // } else {
      //   ElMessage.error('获取停车场详情失败')
      // }
    } catch (error) {
      ElMessage.error('获取停车场详情失败')
      console.error('获取停车场详情失败', error)
      isLoading.value = false
    }
  }

  // 图片上传相关
  const handleImageChange = (file: any) => {
    // 实际项目中应该上传到服务器，这里简单模拟
    const reader = new FileReader()
    reader.onload = (e: any) => {
      imageUrl.value = e.target.result
      form.imageUrl = e.target.result
    }
    reader.readAsDataURL(file.raw)
  }

  // 表单提交
  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          // 设置更新时间
          form.updateTime = new Date().toISOString()

          // 模拟API请求
          isLoading.value = true
          setTimeout(() => {
            // 实际项目中应该调用API保存数据
            isLoading.value = false
            ElMessage.success(isEdit.value ? '停车场信息更新成功' : '停车场添加成功')
            router.push('/parking/ParkingList')
          }, 1000)

          // 实际API调用示例:
          // const service = isEdit.value
          //   ? parkingService.updateParkingLot(form)
          //   : parkingService.createParkingLot(form)
          //
          // const res = await service
          // if (res.code === 200) {
          //   ElMessage.success(isEdit.value ? '停车场信息更新成功' : '停车场添加成功')
          //   router.push('/parking/ParkingList')
          // } else {
          //   ElMessage.error(res.message || '操作失败')
          // }
        } catch (error) {
          console.error('保存停车场信息失败', error)
          ElMessage.error('保存停车场信息失败')
          isLoading.value = false
        }
      } else {
        ElMessage.warning('请正确填写表单信息')
        return false
      }
    })
  }

  // 确认删除
  const confirmDelete = () => {
    ElMessageBox.confirm('确认删除该停车场信息?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          isLoading.value = true

          // 模拟API请求
          setTimeout(() => {
            isLoading.value = false
            ElMessage.success('删除成功')
            router.push('/parking/ParkingList')
          }, 1000)

          // 实际API调用示例:
          // const res = await parkingService.deleteParkingLot(parkingLotId.value)
          // if (res.code === 200) {
          //   ElMessage.success('删除成功')
          //   router.push('/parking/ParkingList')
          // } else {
          //   ElMessage.error(res.message || '删除失败')
          // }
        } catch (error) {
          console.error('删除停车场失败', error)
          ElMessage.error('删除停车场失败')
          isLoading.value = false
        }
      })
      .catch(() => {})
  }

  // 返回列表
  const goBack = () => {
    router.push('/parking/ParkingList')
  }

  onMounted(() => {
    fetchParkingLotDetail()
  })
</script>

<style lang="scss" scoped>
  .parking-edit {
    .form-section-title {
      position: relative;
      padding-bottom: 8px;

      .form-section-line {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: var(--el-border-color-light);
      }
    }

    .avatar-uploader {
      .avatar {
        width: 300px;
        height: 150px;
        display: block;
        object-fit: cover;
      }

      .avatar-uploader-wrapper {
        width: 300px;
        height: 150px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;

        &:hover {
          border-color: var(--el-color-primary);
        }

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
        }
      }
    }
  }
</style>
